import React from 'react'

class UncontrolledDemo extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: 'ionluo',
            flag: true
        }
        this.nameInputRef = React.createRef()
        this.flagInputRef = React.createRef()
        this.fileInputRef = React.createRef()
    }
    render() {
        return <div>
            <h3>非受控组件</h3>
            {/* input defaultValue */}
            <div>
                {/* 使用defaultValue而不是value，使用ref获取结果 */}
                <input type="text" defaultValue={this.state.name} ref={this.nameInputRef} /> <br />
                {/* state并不会随着改变 */}
                <span>state.name: {this.state.name}</span> <br />
                <button onClick={this.alertName}>alert name</button><br /><br />
            </div>
            {/* checkbox defaultChecked */}
            <div>
                {/* 使用defaultChecked而不是checked，使用ref获取结果 */}
                <input type="checkbox" defaultChecked={this.state.flag} ref={this.flagInputRef} /><br />
                {/* state并不会随着改变 */}
                <span>state.flag: {this.state.flag}</span><br />
                <button onClick={this.alertFlag}>alert flag</button><br /><br />
            </div>
            <div>
                {/* 使用ref获取结果 */}
                <input type="file" ref={this.fileInputRef} /><br />
                <button onClick={this.alertFile}>alert file name</button>
            </div>
        </div>
    }
    alertName = () => {
        const elem = this.nameInputRef.current
        alert(elem.value)
    }
    alertFlag = () => {
        const elem = this.flagInputRef.current
        alert(elem.checked)
    }
    alertFile = () => {
        const elem = this.fileInputRef.current
        alert(elem.files[0].name)
    }
}

export default UncontrolledDemo